#include "command.h"

void handler_login(int client_fd, data msg,char *work_path,MYSQL *mysql,char *username,char *newpath){
    //两个字符数组分别来记录用户名和密码
    char user_name[512] = {0};
    char password[512] = {0};
    char *token = strtok(msg.args,"&");
    if(token != NULL){
        //获取用户名
        memcpy(user_name,token,strlen(token));
    }
    token = strtok(NULL,"&");
    if(token != NULL){
        //获取密码
        memcpy(password,token,strlen(token));
    }
    //记录sql语句和日志信息
    char query_buf[1024] = {0};
    char buf_log[1024] = {0};
    MYSQL_RES *result;
    MYSQL_ROW row;
    int flag = 1;

    //获取对应用户的盐值和hash密码
    sprintf(query_buf,"select `user_pwd_hash`,`salt` from user where user_name = '%s'",user_name);
    print_sql_to_log("DEBUG",user_name,query_buf);
    mysql_query(mysql,query_buf);

    //接收查询的结果
    result = mysql_store_result(mysql);
    if(result == NULL || (mysql_num_rows(result) == 0)){
        //说明服务器没有这个用户
        flag = -1;
        send(client_fd,&flag,sizeof(int),MSG_NOSIGNAL);
        strcpy(username,"");
        //释放接收的数据
        mysql_free_result(result);
        return;
    }

    //到这里说明有这个用户名，那么就计算当前的密码加盐后的hash密码
    //row[0]:hash密码
    //row[1]:盐值
    row = mysql_fetch_row(result);
    char *hashed_password = NULL; //接收生成的哈希密码
    char crypt_format[65] = {0}; //存储当前发过来的密码生成的hash密码
    snprintf(crypt_format,sizeof(crypt_format),"$2a$08$%s",row[1]);
    //计算hash密码
    hashed_password = crypt(password,crypt_format);
    printf("密码+盐值生成的hash密码:%s\n",hashed_password);

    if(strcmp(row[0],hashed_password) == 0){
        //说明hash密码对应上了，说明登录成功
        flag = 1;
        //返回1这个标记位
        send(client_fd,&flag,sizeof(int),MSG_NOSIGNAL);
        memset(buf_log,0,sizeof(buf_log));
        sprintf(buf_log,"(%s) 登录成功!",user_name);
        log_log("INFO","SERVER",buf_log);
        //更新外部的username
        strcpy(username,user_name);
        char cur_path[2048] = {0};
        getcwd(cur_path,sizeof(cur_path));
        strcat(cur_path,"/");
        strcat(cur_path,user_name);
        strcpy(work_path,cur_path);
        strcpy(newpath,work_path);
    }else{
        //说明密码错误，需要重新登录
        flag = 0;
        //返回0这个标记位
        send(client_fd,&flag,sizeof(int),MSG_NOSIGNAL);
        memset(buf_log,0,sizeof(buf_log));
        sprintf(buf_log,"(%s) 登录失败，密码不正确...",user_name);
        strcpy(username,"");
        log_log("ERROR","SERVER",buf_log);
    }
    //释放查到的结果
    mysql_free_result(result);
}